﻿using System;
using System.Diagnostics;
using Atha.Contracts;
using Atha.Extensions.Strings;

namespace Atha.Languages
{
	public abstract class ScriptTestRunContextBase : ITestRunContext<AggregateTestResult>
	{
		public ScriptTestRunContextBase(string name, string script)
		{
			this.Name = name;
			this.Script = script;
		}

		public string Name { get; private set; }

		public string Script { get; private set; }

		public AggregateTestResult Execute()
		{
			var testRunResultBuilder = new TestRunResultBuilder();

			try
			{
				this.OnExecute(this.Script, testRunResultBuilder);
			}
			catch (Exception exception)
			{
				Debug.WriteLine("Error: {0}".FormatWith(exception.Message));

				testRunResultBuilder.AddResult(new ExceptionTestResult(exception));
			}

			return new AggregateTestResult(this.Name, testRunResultBuilder.Results);
		}

		protected abstract void OnExecute(string script, ITestRunResultBuilder testRunResultBuilder);
	}
}